package com.jc.nio.thread;

import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import com.jc.nio.thread.Worker;

/**
 * 
 * 这是一个Thread线程组管理类，对worker的封装，负责对里面的线程进行管理，包括其中的idle线程
 * 
 * @author Joeson
 * @since 2014/05
 * @version 01
 * 
 */
public class WorkerGroup
{
	private Worker[] workers;

	/**
	 * woker处理线程数目
	 */
	private int size;

	/**
	 * 空闲的开始位置，也就是下一个被调用的线程worker
	 */
	private AtomicInteger idled;

	/**
	 * worker线程的优先级
	 */
	private int threadPriority = Thread.NORM_PRIORITY;

	public WorkerGroup()
	{

	}

	public WorkerGroup(int workerSize)
	{
		this.size = workerSize;

		this.idled = new AtomicInteger(0);

		initWorker();
	}

	private void initWorker()
	{
		workers = new Worker[size];

		for (int i = 0; i < size; i++)
		{
			workers[i] = new Worker();
			Thread thread = new Thread(workers[i], "worker--" + i);
			thread.setDaemon(true);
			thread.setPriority(threadPriority);
			thread.start();
		}

	}

	/**
	 * 获取woker线程
	 * 
	 * @return
	 */
	public synchronized Worker getWorker()
	{
		int tmp = idled.getAndSet((idled.get() + 1) % size);
		return workers[tmp];
	}

}
